package com.write.program.util;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Endstart
 * Date: 2020-03-12
 * Time: 14:54
 */
public class FileUtil {

    public static byte[] readFileByte(String filePath) {
        try {
            FileInputStream fileInputStream = new FileInputStream(URLDecoder.decode(filePath));
            byte[] bytes = new byte[fileInputStream.available()];
            int index = 0;

            byte[] readBytes = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(readBytes)) != -1) {
                for (int i = 0; i < readLen; i++) {
                    bytes[index++] = readBytes[i];
                }
            }
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> readFileString(String file) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String line = null;
            List<String> lines = new ArrayList<>();
            while ((line = bufferedReader.readLine()) != null) {
                lines.add(line);
            }
            return lines;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void writeFile(String file, List<String> lines) {
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
            for (String line : lines) {
                bufferedWriter.write(line + System.lineSeparator());
            }
            bufferedWriter.flush();
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getFileContent(String filename) {
        String content = null;
        try {
            content = new String(Files.readAllBytes(Paths.get(filename)), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }



}
